<?PHP	
	require 'utils.php';	
	
	//Main function, compares UIDs from Cookies & DB, returns "true" if equal
	function SessionExist()
	{
		//SetCookieLive('key1', '303031');
		//SetCookieLive('key2', '404041');		
		$vResult = false;
		$vIDsFromIP = getIDFromIP();
		$vIDFromCookies = getIDFromCookies();
		if(count($vIDsFromIP) > 0 and intval($vIDFromCookies) > 0)
		{
			foreach ($vIDsFromIP as $vIDbyIP)
			{
				if($vIDbyIP == $vIDFromCookies)
				{	
					$vResult = true;
					break;
				}			
			}
		}
		return $vResult;
	}
	
	function getUserID()
	{
		$vResult = -1;
		$vIDsFromIP = getIDFromIP();
		$vIDFromCookies = getIDFromCookies();
		if(count($vIDsFromIP) > 0 and intval($vIDFromCookies) > 0)
		{
			foreach ($vIDsFromIP as $vIDbyIP)
			{
				//Trace('Comapring: ID by IP = ' . $vIDbyIP . ' and Id by Cookies = ' . $vIDFromCookies);
				if($vIDbyIP == $vIDFromCookies)
				{	
					$vResult = $vIDbyIP;
					break;
				}			
			}
		}
		return $vResult;
	}	
	//Getting UID from DB using users IP
	function getIDFromIP()
	{
		$vIPCondition = getIPCondition();			
		$vQuery = "SELECT user_id FROM dikar2011_session WHERE " . $vIPCondition;		
		$vResults = mysql_query($vQuery);
		$vResult = array();		
		while($vLine = mysql_fetch_assoc($vResults))
		{		
			$vResult[] = $vLine['user_id'];			
		}
		return $vResult;
	}
	
	//Function perfoms ip extraction and return SQL query based on extracted IP
	function getIPCondition()
	{
		$ClientIP = $_SERVER['REMOTE_ADDR'];
		$vResult = array();
		$vResult = explode('.', $ClientIP);		
		return "ipa=" . $vResult[0] . " AND ipb=" . $vResult[1] . " AND ipc=" . $vResult[2] . " AND ipd=" . $vResult[3];
	}
	
	//Function provides Cookies chek & SQL query execution with cookie-delivered keys
	function getIDFromCookies()
	{
		$vKey1 = -1;
		$vKey2 = -1;
		if (isset($_COOKIE['key1']))
			$vKey1 = $_COOKIE['key1'];
		if (isset($_COOKIE['key2']))		
			$vKey2 = $_COOKIE['key2'];		
		$vCondition = "key1=" . $vKey1 . " AND key2=" . $vKey2;
		$vQuery = "SELECT id FROM dikar2011_obj WHERE " . $vCondition;		
		$vResult = -1;
		$vResults = mysql_query($vQuery);		
		while($vLine = mysql_fetch_assoc($vResults))			
			$vResult = $vLine['id'];
		//Trace('User ID by cookies: ' . $vResult);
		return $vResult;
	}
?>